<script setup>
import {computed, ref} from 'vue'
import {onShow} from '@dcloudio/uni-app'
import {get, post} from '@/request/request'
import TnForm from '@tuniao/tnui-vue3-uniapp/components/form/src/form.vue'
import TnFormItem from '@tuniao/tnui-vue3-uniapp/components/form/src/form-item.vue'
import TnButton from '@tuniao/tnui-vue3-uniapp/components/button/src/button.vue'
import TnInput from '@tuniao/tnui-vue3-uniapp/components/input/src/input.vue'
import TnTitle from '@tuniao/tnui-vue3-uniapp/components/title/src/title.vue'
import TnRadio from '@tuniao/tnui-vue3-uniapp/components/radio/src/radio.vue'
import TnRadioGroup from '@tuniao/tnui-vue3-uniapp/components/radio/src/radio-group.vue'
import TnCheckbox from '@tuniao/tnui-vue3-uniapp/components/checkbox/src/checkbox.vue'
import TnCheckboxGroup from '@tuniao/tnui-vue3-uniapp/components/checkbox/src/checkbox-group.vue'
import TnPicker from '@tuniao/tnui-vue3-uniapp/components/picker/src/picker.vue'


//性别
const genders = ref([{
  label: '男',
  value: 1,
}, {
  label: '女',
  value: 2,
}, {
  label: '均可',
  value: 3,
}])
const formRef = ref()
const gradeCourseData = ref([])//年级课程
const gradesType = ref([]);//年级所属阶段
const gradesTypeId = ref('');//年级所属阶段
const gradesTypeName = ref('请选择阶段');//年级所属阶段
const openGradesType = ref(false);//年级所属阶段
const course = ref([]);//课程
const courseId = ref([]);//
const openCourse = ref(false);//
const courseName = ref('请选择科目');//
//年级
const openGrade = ref(false)
const grade = computed(() => {
  return course.value.map(item => {
    return {
      label: item.label,
      value: item.value
    }
  });
})
const reginData = ref([])//地区
const openregin = ref(false);
const reginValue = ref([]);
const reginName = ref('请选择地区');

const openAppTime = ref(false);
const appTimeOptions = ref([
  {label: '1小时', value: 1},
  {label: '2小时', value: 2},
  {label: '3小时', value: 3},
  {label: '4小时', value: 4},
  {label: '5小时', value: 5},
  {label: '6小时', value: 6},
  {label: '7小时', value: 7},
  {label: '8小时', value: 8},
  {label: '9小时', value: 9},
  {label: '10小时', value: 10},
])
//周天数据
const weekDays = ref([
  {label: '周一', value: 1},
  {label: '周二', value: 2},
  {label: '周三', value: 3},
  {label: '周四', value: 4},
  {label: '周五', value: 5},
  {label: '周六', value: 6},
  {label: '周日', value: 7}]);
// 表单数据
const formData = ref({
  userName: '', //姓名
  phone: '', //手机号
  grade: '', //年级
  courseId: '', //课程
  situation: '', //情况
  sex: 1, //性别
  sexName: '男',
  province: '', //省
  city: '', //市
  county: '', //区
  address: '', //地址
  house: '', //门牌号
  tSex: 3, //老师性别
  price: '', //课酬
  tSituation: '', //老师情况
  res: 0, //授课时间
  appTime: 2, //每次授课时间
  day: '', //授课时间天数
  gName: '' //输入年级
})

onShow(() => {
  getGradeCourse();
  gatregin();
})

// 地区
const gatregin = async () => {
  get('/public_api/get_regin').then(res => {
    const {data} = res;
    // 处理地区数据
    reginData.value = convertData(data)
  })
}
// 获取年级和课程
const getGradeCourse = async () => {
  get('/public_api/get_grade_course').then(res => {
    const {data} = res;
    gradeCourseData.value = data;
    //年级阶段处理
    gradesType.value = data.map(item => {
      return {
        label: item.name,
        value: item.id
      }
    });
  })
}


// 选择阶段
const selectGradeType = (e) => {

  const findChildren = gradeCourseData.value.find(item => item.id === e);
  const course_list = findChildren.grade.filter(item => item.course.length > 0)
  course.value = convertCourseData(course_list);
  const findName = gradesType.value.find(item => item.value == e);
  gradesTypeName.value = findName.label;
  courseName.value = '请选择科目';
}
//处理数据
const convertCourseData = (arr) => {
  return arr.map(maps => {
    const {name, id} = maps;
    const children = maps.course ? convertCourseData(maps.course) : null; // 递归处理子级数据
    const obj = {
      label: name,
      value: id,
    };
    if (children != null) {
      obj.children = children;
    }
    return obj;
  })
}
// 选择课程
const selectCourse = (e) => {
  if (e.length > 1) {
    courseName.value = getNameByIds(e).pop();
    formData.value.grade = e[0];
    formData.value.courseId = e[1];
  } else {
    courseName.value = '请选择科目';
    formData.value.courseId = '';
  }
}

//选择每次时间
const selectAppTime = (e) => {
  formData.value.appTime = e;
}
//选择授课时间
const selectWeekValue = (value) => {
  console.log(value);
  formData.value.res = value.length > 0 ? 1 : 0;
  formData.value.day = value;
}
// 选择地区
const selectregin = (e) => {
  console.log(e);
  reginValue.value = e;
  formData.value.province = e[0];
  formData.value.city = e[1];
  formData.value.county = e[2];
  reginName.value = getreginNameByIds(e);
}


const getreginNameByIds = (ids) => {
  const names = [];
  let currentLevel = reginData.value;
  for (let id of ids) {
    const item = currentLevel.find(item => item.value === id);
    if (item) {
      names.push(item.label);
      currentLevel = item.children; // Update current level to the children of the current item
    } else {
      break; // Break the loop if item not found
    }
  }

  return names.join(', ');
}

const insertPrice = (value) => {
  const regex = /^\d+(\.\d+)?$/;
  if (!regex.test(value)) {
    formData.value.price = '';
  }
}


const getNameByIds = (ids) => {
  const names = [];
  let currentLevel = course.value;
  for (let id of ids) {
    const item = currentLevel.find(item => item.value === id);
    if (item) {
      names.push(item.label);
      currentLevel = item.children; // Update current level to the children of the current item
    } else {
      break; // Break the loop if item not found
    }
  }
  return names;
}
//处理数据
const convertData = (arr) => {
  return arr.map(item => {
    const children = item.children && item.children.length ? convertData(item.children) : null; // 递归处理子级数据
    const data = {
      label: item.name,
      value: item.id,
    };
    if (children) {
      data.children = children; // 处理最底层数据
    }
    return data;
  });
}


const gradsClick = () => {
  if (gradesTypeId.value) {
    openCourse.value = true;
  } else {
    uni.showToast({
      title: '请选择年级阶段',
      icon: 'error',
    })
  }
}
//学员男女处理
const genderClick = (e) => {
  const sex = genders.value.find(item => item.value == e);
  formData.value.sex = sex.value;
  formData.value.sexName = e;
}
//规则
const formRules = {
  userName: [{required: true, message: '请输入用户名', trigger: ['change', 'blur']}],
  phone: [
    {
      required: true,
      message: '请输入手机号',
      trigger: ['change', 'blur']
    },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '手机号格式不正确',
      trigger: ['change', 'blur']
    }
  ],
  idCard: [
    {
      required: true,
      message: '请输入身份证号码',
      trigger: ['change', 'blur']
    },
    {
      pattern: /^[1-9]\d{5}(19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[Xx\d]$/,
      message: '身份证号码格式不正确',
      trigger: ['change', 'blur']
    }
  ]
}
//学员男女处理
const tgenderClick = (e) => {
  const sex = genders.value.find(item => item.value == e);
  formData.value.tSex = sex.value;
  formData.value.sexName = e;
}

/* 提交表单 */
const submitForm = () => {
  formRef.value?.validate((valid) => {
    if (valid) {
      post('/order_add', formData.value, {
        "Content-Type": "application/x-www-form-urlencoded",
        "sessionKey": uni.getStorageSync("sessionKey")
      },).then(res => {
        console.log(res);
        const data = res.data;
        if (res.code == 200) {
          uni.navigateTo({
            url: '/pages/order/components/order-info?data=' + JSON.stringify(data)
          });
        } else {
          uni.showToast({
            title: res.message,
          })
        }
      })
      uni.showToast({
        title: '提交成功',
        icon: 'success',
        duration: 2000
      })
    } else {
      if (!formData.value.userName) {
        uni.showToast({
          title: '姓名不能为空',
          icon: 'none',
        })
        return false
      }
      if (!formData.value.phone) {
        uni.showToast({
          title: '手机号不能为空',
          icon: 'none',
        })
        return false
      }
      if (!formData.value.grade) {
        uni.showToast({
          title: '年级不能为空',
          icon: 'none',
        })
        return false
      }
      if (!formData.value.courseId) {
        uni.showToast({
          title: '课程不能为空',
          icon: 'none',
        })
        return false
      }
      if (!formData.value.situation) {
        uni.showToast({
          title: '情况不能为空',
          icon: 'none',
        })
        return false
      }
      if (!formData.value.sex) {
        uni.showToast({
          title: '学员性别不能为空',
          icon: 'none',
        })
        return false
      }
      if (!formData.value.province || formData.value.province === 0) {
        uni.showToast({
          title: '地区不能为空',
          icon: 'none',
        })
        return false
      }
      if (!formData.value.city || formData.value.city === 0) {
        uni.showToast({
          title: '城市不能为空',
          icon: 'none',
        })
        return false
      }
      if (!formData.value.county || formData.value.county === 0) {
        uni.showToast({
          title: '地区不能为空',
          icon: 'none',
        })
        return false
      }
      if (!formData.value.address) {
        uni.showToast({
          title: '地址不能为空',
          icon: 'none',
        })
        return false
      }
      if (!formData.value.house) {
        uni.showToast({
          title: '门牌号不能为空',
          icon: 'none',
        })
        return false
      }
      if (!formData.value.tSex) {
        uni.showToast({
          title: '教师性别不能为空',
          icon: 'none',
        })
        return false
      }
      if (!formData.value.price) {
        uni.showToast({
          title: '价格不能为空',
          icon: 'none',
        })
        return false
      }
      if (!formData.value.tSituation) {
        uni.showToast({
          title: '教师情况不能为空',
          icon: 'none',
        })
        return false
      }
      if (!formData.value.res) {
        uni.showToast({
          title: '授课时间不能为空',
          icon: 'none',
        })
        return false
      }
      if (!formData.value.appTime) {
        uni.showToast({
          title: '每次授课时间不能为空',
          icon: 'none',
        })
        return false
      }
      if (!formData.value.day) {
        uni.showToast({
          title: '授课时间不能为空',
          icon: 'none',
        })
        return false
      }
      if (!formData.value.gName) {
        uni.showToast({
          title: '年级不能为空',
          icon: 'none',
        })
        return false
      }
    }
  })
}

</script>

<template>
  <view class="app">
    <TnForm ref="formRef" :model="formData" :rules="formRules">
      <view style="width: 100%;display: flex;align-items: center;justify-content: center;margin-bottom: 20rpx;">
        <TnTitle title="学员信息" size="xl"/>
      </view>
      <TnFormItem label="姓名" prop="userName">
        <TnInput placeholder="请输入姓名" :underline="true" size="sm" v-model="formData.userName"/>
      </TnFormItem>
      <TnFormItem label="手机号" prop="phone">
        <TnInput :maxlength="11" placeholder="请输入手机号" type="number" :underline="true" size="sm"
                 v-model="formData.phone"/>
      </TnFormItem>
      <view class="d-flex">
        <TnFormItem label="科目">
        </TnFormItem>
        <view class="subjects" @click="() => (openGradesType = true)">{{ gradesTypeName }}</view>
        <view class="subjects" @click="gradsClick">{{ courseName }}</view>
      </view>
      <view style="width: 100%;display: flex;justify-content: space-around;border-bottom: 2rpx #e6e6e6 solid;">
        <TnFormItem label="情况">
        </TnFormItem>
        <textarea placeholder="请详细描述一下孩子的情况，如年级、学习情况等。" style="text-indent: 10rpx;
    padding-top: 10rpx;" v-model="formData.situation"/>
      </view>
      <TnFormItem label="学员性别">
        <view style="width: 100%;display: flex;justify-content: space-evenly;">
          <TnRadioGroup v-model="formData.sex" active-color="#0d57d6" size="lg" @change="genderClick">
            <template v-for="item in genders">
              <template v-if="item.value < 3">
                <TnRadio :label="item.value">{{ item.label }}</TnRadio>
              </template>
            </template>
          </TnRadioGroup>
        </view>
      </TnFormItem>
      <TnFormItem label="年级">
        <TnInput placeholder="请填写年级" :underline="true" size="sm" v-model="formData.gName"/>
      </TnFormItem>
      <TnFormItem label="地区">
        <view @click="() => (openregin = true)">{{ reginName }}</view>
      </TnFormItem>
      <TnFormItem label="地址" prop="address">
        <TnInput placeholder="请填写交叉路或小区" :underline="true" size="sm" v-model="formData.address"/>
      </TnFormItem>
      <TnFormItem label="门牌号">
        <TnInput placeholder="请填写门牌号" :underline="true" size="sm" v-model="formData.house"/>
      </TnFormItem>
      <view class="d-flex">
        <TnFormItem label="授课时间">
        </TnFormItem>
        <view class="subjects" :class="{ 'border-color': formData.res == 0 }"
              @click="() => (formData.res = 0, formData.day = '')">一周1次
        </view>
        <view class="subjects" @click="() => (openAppTime = true)">每次{{ formData.appTime }}小时</view>
      </view>
      <TnCheckboxGroup v-model="formData.day" size="lg" @change="selectWeekValue">
        <view v-for="(item, index) in weekDays" :key="index">
          <TnCheckbox size="lg" :label="item.value" active-color="#0052D9">{{ item.label }}</TnCheckbox>
        </view>
      </TnCheckboxGroup>
      <view style="margin-top: 100rpx;display: flex;align-items: center;justify-content: center;margin-bottom: 30rpx">
        <TnTitle title="教师信息" size="xl"/>
      </view>
      <TnFormItem label="教师性别">
        <view style="width: 100%;display: flex;justify-content: space-evenly;">
          <TnRadioGroup v-model="formData.tSex" active-color="#0d57d6" size="lg" @change="tgenderClick">
            <view style="margin-left: 130rpx;display: flex">
              <template v-for="item in genders">
                <TnRadio :label="item.value">{{ item.label }}</TnRadio>
              </template>
            </view>
          </TnRadioGroup>
        </view>
      </TnFormItem>
      <TnFormItem label="课酬">
        <view style="margin-left: 50rpx;display: flex;align-items: center;">
          <TnInput type="number" placeholder="请输入您能接受的价格如：80" v-model="formData.price" :border="false"
                   style="width: 80%;" :underline="true" @change="insertPrice"/>
          /小时
        </view>
      </TnFormItem>
      <view
          style="width: 100%;display: flex;justify-content: space-between;border-bottom: 2rpx #e6e6e6 solid;margin: 10rpx">
        <TnFormItem label="情况">
        </TnFormItem>
        <textarea placeholder="请详细描述一下对老师的要求，如大学生女教员，有经验等。" style="text-indent: 10rpx;
    padding-top: 10rpx;" v-model="formData.tSituation"/>
      </view>
    </TnForm>
    <view class="tn-mt tn-flex-center">
      <TnButton :width="686" bg-color="#0052D9" text-color="#FFF" type="primary" size="xl" font-size="32"
                @click="submitForm">提交
      </TnButton>
    </view>
  </view>
  <!-- 年级阶段 -->
  <TnPicker v-model="gradesTypeId" v-model:open="openGradesType" :data="gradesType" @confirm="selectGradeType"
            confirm-color="#0052D9"/>
  <!-- 科目 -->
  <TnPicker v-model="courseId" v-model:open="openCourse" :data="course" @confirm="selectCourse"
            confirm-color="#0052D9"/>
  <!-- 年级 -->
  <!-- <TnPicker v-model="formData.grade" v-model:open="openGrade" :data="grade" @confirm="selectGrade" /> -->

  <!-- 每次几个小时 -->
  <TnPicker v-model="formData.appTime" v-model:open="openAppTime" :data="appTimeOptions" @confirm="selectAppTime"
            confirm-color="#0052D9"/>
  <!-- 选择地区 -->
  <TnPicker v-model="reginValue" v-model:open="openregin" :data="reginData" @confirm="selectregin"
            confirm-color="#0052D9"/>
</template>

<style lang="scss" scopd>
@import './index.scss';

.app {
  padding: 20rpx;
  padding-bottom: 50rpx;

  .d-flex {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-bottom: 2rpx #e6e6e6 solid;

    .subjects {
      width: 236rpx;
      height: 76rpx;
      border-radius: 999rpx;
      border: 2rpx solid #DCDCDC;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 28rpx;
      margin-bottom: 20rpx;
    }
  }
}
</style>